<?php


namespace App\Service;

use App\Concern\BaseDao;
use App\Constants\SettleAccessType;
use App\Constants\XZXResponseCode;
use App\Model\Dao\BankInfoDao;
use App\Model\Dao\ChannelInfoDao;
use App\Model\Dao\TradeOrderDetailDao;
use App\Model\Dao\TradeOrderDisDao;
use App\Model\Dao\TradeOrderForceSuccessSingleDao;
use App\Model\Dao\TradeOrderFrozenDao;
use App\Model\Dao\TradeOrderRefundBankDao;
use App\Model\Dao\TradeOrderRefundDao;
use App\Model\Dao\TradeOrderThawDao;
use App\Model\Enum\OrderDetailDisEnum;
use App\Model\Enum\OrderDetailFrozenEnum;
use App\Model\Enum\OrderDetailRefundEnum;
use App\Model\Enum\OrderDetailThawEnum;
use App\Model\Enum\OrderHandleStatusEnum;
use App\Model\Enum\OrderReviewStatusEnum;
use App\Model\Enum\OrderSettleStatusEnum;
use App\Model\Enum\StatusEnum;
use App\Utils\CustomUtils;
use Hyperf\Database\Query\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Utils\Arr;

/**
 * Class TradeOrderReviewService
 * 订单业务审核流
 *
 * @package App\Service
 */
class TradeOrderReviewService {

    /**
     * @var TradeOrderRefundService
     * @Inject()
     */
    private $TradeOrderRefundService;

    /**
     * @var SettleService
     * @Inject()
     */
    private $SettleService;

    /**
     * @Inject()
     * @var TradeOrderFrozenDao
     */
    private $TradeOrderFrozenDao;

    /**
     * @Inject()
     * @var TradeOrderThawDao
     */
    private $TradeOrderThawDao;

    /**
     * @Inject()
     * @var TradeOrderDisDao
     */
    private $TradeOrderDisDao;

    /**
     * @Inject()
     * @var TradeOrderRefundDao
     */
    private $TradeOrderRefundDao;

    /**
     * @Inject()
     * @var TradeOrderForceSuccessSingleDao
     */
    private $TradeOrderForceSuccessSingleDao;

    /**
     * @Inject()
     * @var TradeOrderDetailDao
     */
    private $TradeOrderDetailDao;

    /**
     * @Inject()
     * @var BankInfoDao
     */
    private $BankInfoDao;

    /**
     * @Inject()
     * @var ChannelInfoDao
     */
    private $ChannelInfoDao;

    protected function _getOrderList (BaseDao $OrderDao, $tradeNoList, $mchIdList = null) {

        $orderList = [];

        // 遍历获取各个流水号,最新的订单记录
        foreach ($tradeNoList as $tradeNo) {

            $builder = Db::table($OrderDao::table());

            !is_null($mchIdList) && $builder->whereIn('mchId', $mchIdList);
            $builder->where('tradeNo', $tradeNo);

            $builder->orderBy('createTime', 'desc'); // 获取最新

            $order = $builder->first();

            if (!!$order) {
                array_push($orderList, $order);
            }
        }

        return $orderList;
    }

    /**
     * 补单审核
     *
     * @param $params
     *
     * @return array
     * @throws \Throwable
     */
    public function handleForceSuccessReview ($params) {

        $OrderDao = $this->TradeOrderForceSuccessSingleDao;

        $isApprove   = Arr::get($params, 'isApprove');
        $reviewLevel = Arr::get($params, 'reviewLevel');

        $tradeNoList = Arr::get($params, 'tradeNoList', []);
        $tradeNoList = array_unique($tradeNoList);
        $mchIdList   = Arr::get($params, 'mchIdList', null);

        // 查询相关订单
        $orderList = $this->_getOrderList($OrderDao, $tradeNoList, $mchIdList);

        // 筛选出无效的ID列表
        $failTradeNoList = $this->_filterFailTradeNoList($tradeNoList, $orderList, $reviewLevel);


        if (!empty($failTradeNoList)) {
            return CustomUtils::buildError('部分订单不符合审核条件', XZXResponseCode::FAILED_CODE, ['failTradeNoList' => $failTradeNoList]);
        }

        $ret = CustomUtils::buildSuccess();
        Db::beginTransaction();

        try {

            // 更新订单审核状态
            $update = $this->_parseStatusParams($reviewLevel, $isApprove, $params['createBy'], $params['remark']);
            $idList = array_column($orderList, 'id');

            $OrderDao->updateWhere(function (Builder $builder) use ($idList) {
                $builder->whereIn('id', $idList);
            }, $update);

            // 写入交易变更日志
            $orderLogList = [];
            foreach ($orderList as $order) {
                array_push($orderLogList, array_merge($order, $update, ['createBy' => $params['createBy']]));
            }
            ApplicationContext::getContainer()->get(TradeOrderForceSuccessService::class)->addOrderLog($orderLogList);

            // 更新订单详情
            foreach ($orderList as $order) {
                $this->TradeOrderDetailDao->handleForceSuccess($order['orderId'], $update['handleStatus'] + 1, $order['transAmount']);
            }

            Db::commit();

            // 通知出入账
            foreach ($orderList as $order) {

                $settleParams = [
                    'accessType'   => SettleAccessType::ACCESS_TYPE_TRADE_ORDER_FORCE_SUCCESS,
                    'orderId'      => $order['orderId'],
                    'handleStatus' => $update['handleStatus'],
                    'mchNo'        => $order['mchNo'],
                    'tradeNo'      => $order['tradeNo'],
                ];

                $this->SettleService->addMq($order['mchId'], $settleParams);
            }

        } catch (\Throwable $e) {
            Db::rollBack();
            $ret = CustomUtils::buildError($e->getMessage());
        }

        return $ret;
    }

    private function handleRefundReviewSingle ($params) {

        $isApprove   = Arr::get($params, 'isApprove');
        $reviewLevel = Arr::get($params, 'reviewLevel');
        $orderRefund = Arr::get($params, 'orderRefund');

        $updateBankStatus = null;

        try {
            Db::beginTransaction();

            // 更新订单审核状态
            $update = $this->_parseStatusParams($reviewLevel, $isApprove, $params['createBy'], $params['remark']);
            $this->TradeOrderRefundDao->update($orderRefund['id'], $update);

            if ($isApprove && $reviewLevel == 2) {
                // 复审通过

                // 反查订单
                $orderDetail = $this->TradeOrderDetailDao->getWhere(['tradeNo' => $orderRefund['tradeNo']]);
                if (!$orderDetail) {
                    throw new \Exception('未找到订单详情');
                }

                // 反差通道
                $channel = $this->ChannelInfoDao->get($orderDetail['channelId']);
                if (!$channel) {
                    throw new \Exception('未找到支付通道信息');
                }

                if ($channel['canRefund']) {
                    // 支持API退款

                    $refundList = $this->_doBankRefund(array_merge($orderRefund, $update), $orderDetail, $params['createBy']);
                    $re         = $this->_doBankRefundAndAccountTrans($refundList);
                    $re         = reset($re['data']);

                    if (CustomUtils::isSuccess($re)) {
                        // API退款成功

                        $updateBankStatus = [
                            'bankRefundStatus' => 1,
                            'bankRefundTimes'  => Db::raw("`bankRefundTimes` + 1"),
                        ];
                    }
                    else {

                        $updateBankStatus = [
                            'bankRefundStatus' => 2,
                            'bankRefundTimes'  => Db::raw("`bankRefundTimes` + 1"),
                        ];

                        throw new \Exception($re['msg']);
                    }
                }
            }

            // 更新订单详情
            $this->TradeOrderDetailDao->handleRefund($orderRefund['orderId'], $update['handleStatus'] + 1, $orderRefund['transAmount'], $orderRefund['transSettleAmount']);

            // 写入交易变更日志
            $orderLog = array_merge($orderRefund, $update, ['createBy' => $params['createBy']]);
            $this->TradeOrderRefundService->addOrderLog([$orderLog]);

            Db::commit();

            // 通知出入账处理
            $settleParams = [
                'accessType'   => SettleAccessType::ACCESS_TYPE_TRADE_ORDER_REFUND,
                'refundId'     => $orderRefund['id'],
                'handleStatus' => $update['handleStatus'],
                'mchNo'        => $orderRefund['mchNo'],
                'tradeNo'      => $orderRefund['tradeNo'],
            ];
            $this->SettleService->addMq($orderRefund['mchId'], $settleParams);

        } catch (\Throwable $e) {
            Db::rollBack();
            return CustomUtils::buildError($e->getMessage());
        } finally {
            if (!!$updateBankStatus) {
                $this->TradeOrderRefundDao->update($orderRefund['id'], $updateBankStatus);
            }
        }


        return CustomUtils::buildSuccess();
    }

    /**
     * 退款订单审核
     *
     * @param $params
     *
     * @return array
     * @throws \Throwable
     */
    public function handleRefundReview ($params) {

        $OrderDao = $this->TradeOrderRefundDao;

        $isApprove   = Arr::get($params, 'isApprove');
        $reviewLevel = Arr::get($params, 'reviewLevel');

        $mchIdList   = Arr::get($params, 'mchIdList', null);
        $tradeNoList = Arr::get($params, 'tradeNoList', []);
        $tradeNoList = array_unique($tradeNoList);

        // 查询相关订单
        $orderList = $this->_getOrderList($OrderDao, $tradeNoList, $mchIdList);

        // 筛选出无效tradeNo列表
        $failTradeNoList    = $this->_filterFailTradeNoList($tradeNoList, $orderList, $reviewLevel);
        $successTradeNoList = [];

        if (!empty($failTradeNoList)) {
            // 返回错误信息
            return CustomUtils::buildError('部分订单不符合审核条件', XZXResponseCode::FAILED_CODE, [
                'failTradeNoList'    => $failTradeNoList,
                'successTradeNoList' => $successTradeNoList,
            ]);
        }

        $failTradeNoList    = [];
        $successTradeNoList = [];

        foreach ($orderList as $orderRefund) {
            $params['orderRefund'] = $orderRefund;
            $re                    = $this->handleRefundReviewSingle($params);

            if (CustomUtils::isError($re)) {
                array_push($failTradeNoList, [
                    'tradeNo' => $orderRefund['tradeNo'],
                    'reason'  => $re['msg'],
                ]);
            }
            else {
                array_push($successTradeNoList, [
                    'tradeNo' => $orderRefund['tradeNo'],
                ]);
            }
        }

        $data = [
            'failTradeNoList'    => $failTradeNoList,
            'successTradeNoList' => $successTradeNoList,
        ];

        if (count($orderList) == 1) {
            if (empty($failTradeNoList)) {
                return CustomUtils::buildSuccess($data);
            }
            else {
                return CustomUtils::buildError($failTradeNoList[0]['reason'], XZXResponseCode::FAILED_CODE, $data);
            }
        }
        else {
            if (empty($successTradeNoList)) {
                return CustomUtils::buildError($failTradeNoList[0]['reason'], XZXResponseCode::FAILED_CODE, $data);
            }
            else {
                return CustomUtils::buildSuccess($data);
            }
        }
    }

    protected function _doBankRefundAndAccountTrans ($refundList) {

        return ApplicationContext::getContainer()->get(TradeOrderRefundBankService::class)->doBankRefundAndAccountTrans($refundList);

    }

    protected function _doBankRefund ($order, $detail, $createBy = '') {

        $RateCustomizedService       = ApplicationContext::getContainer()->get(RateCustomizedService::class);
        $TradeOrderRefundBankService = ApplicationContext::getContainer()->get(TradeOrderRefundBankService::class);

        // 处理退款结算金额, 从帐单取出对应汇率转换
        $transRate = json_decode($detail['transRate'], true);
        $reTrans   = $RateCustomizedService->getRefundAmount([
            'platformTransRate' => $transRate['mchToPlatform'],
            'bankTransRate'     => $transRate['platformToBank'],
            'mchTransAmount'    => $order['transAmount'],
        ])['data'];

        $update = [
            'refundId'           => $order['id'],
            'orderId'            => $order['orderId'],
            'tradeNo'            => $order['tradeNo'],
            'relNo'              => $detail['relNo'],
            'mchId'              => $order['mchId'],
            'mchNo'              => $order['mchNo'],
            'bankId'             => $detail['bankId'],
            'channelId'          => $detail['channelId'],
            'channelName'        => $detail['channelName'],
            'bankRefundAmount'   => $reTrans['bankTransAmount'],
            'bankRefundCurrency' => $detail['channelTransCurrency'],
            'createBy'           => $createBy,
        ];

        return $TradeOrderRefundBankService->doAdd($update);
    }

    /**
     * 拒付订单审核
     *
     * @param $params
     *
     * @return array
     * @throws \Throwable
     */
    public function handleDisReview ($params) {

        $OrderDao = $this->TradeOrderDisDao;

        $isApprove   = Arr::get($params, 'isApprove');
        $reviewLevel = Arr::get($params, 'reviewLevel');

        $mchIdList   = Arr::get($params, 'mchIdList', null);
        $tradeNoList = Arr::get($params, 'tradeNoList', []);
        $tradeNoList = array_unique($tradeNoList);

        // 查询订单列表
        $orderList = $this->_getOrderList($OrderDao, $tradeNoList, $mchIdList);

        // 筛选出无效tradeNo列表
        $failTradeNoList = $this->_filterFailTradeNoList($tradeNoList, $orderList, $reviewLevel);

        if (!empty($failTradeNoList)) {
            // 返回错误信息
            return CustomUtils::buildError('部分订单不符合审核条件', XZXResponseCode::FAILED_CODE, ['failTradeNoList' => $failTradeNoList]);
        }

        Db::beginTransaction();

        try {

            // 更新订单审核状态
            $update = $this->_parseStatusParams($reviewLevel, $isApprove, $params['createBy'], $params['remark']);
            $idList = array_column($orderList, 'id');
            $OrderDao->updateWhere(function (Builder $builder) use ($idList) {
                $builder->whereIn('id', $idList);
            }, $update);

            // 写入交易变更日志
            $orderLogList = [];
            foreach ($orderList as $order) {
                array_push($orderLogList, array_merge($order, $update, ['createBy' => $params['createBy']]));
            }
            ApplicationContext::getContainer()->get(TradeOrderDisService::class)->addOrderLog($orderLogList);

            foreach ($orderList as $order) {
                $this->TradeOrderDetailDao->handleDis($order['orderId'], $update['handleStatus'] + 1, $order['transAmount']);
            }

        } catch (\Throwable $e) {
            Db::rollBack();
            throw $e;
        }

        Db::commit();

        // 通知出入账
        foreach ($orderList as $order) {
            $this->SettleService->addMq($order['mchId'], [
                'accessType'   => SettleAccessType::ACCESS_TYPE_TRADE_ORDER_DIS_LOOK_INTO,
                'disId'        => $order['id'],
                'handleStatus' => $update['handleStatus'],
                'mchNo'        => $order['mchNo'],
                'tradeNo'      => $order['tradeNo'],
            ]);
        }

        return CustomUtils::buildSuccess();
    }

    /**
     * 解冻订单审核
     *
     * @param $params
     *
     * @return array
     * @throws \Throwable
     */
    public function handleThawReview ($params) {

        $OrderDao = $this->TradeOrderThawDao;

        $isApprove   = Arr::get($params, 'isApprove');
        $reviewLevel = Arr::get($params, 'reviewLevel');

        $mchIdList   = Arr::get($params, 'mchIdList', null);
        $tradeNoList = Arr::get($params, 'tradeNoList', []);
        $tradeNoList = array_unique($tradeNoList);

        // 查询解冻订单
        $orderList = $this->_getOrderList($OrderDao, $tradeNoList, $mchIdList);

        // 筛选出无效tradeNo列表
        $failTradeNoList = $this->_filterFailTradeNoList($tradeNoList, $orderList, $reviewLevel);

        if (!empty($failTradeNoList)) {
            // 返回错误信息
            return CustomUtils::buildError(XZXResponseCode::getMessage(XZXResponseCode::UNQUALIFIED_ORDER), XZXResponseCode::FAILED_CODE, ['failTradeNoList' => $failTradeNoList]);
        }

        Db::beginTransaction();

        try {

            // 更新订单审核状态
            $update = $this->_parseStatusParams($reviewLevel, $isApprove, $params['createBy'], $params['remark']);
            $idList = array_column($orderList, 'id');
            $OrderDao->updateWhere(function (Builder $builder) use ($idList) {
                $builder->whereIn('id', $idList);
            }, $update);

            // 写入交易变更日志
            $orderLogList = [];
            foreach ($orderList as $order) {
                array_push($orderLogList, array_merge($order, $update, ['createBy' => $params['createBy']]));
            }
            ApplicationContext::getContainer()->get(TradeOrderThawService::class)->addOrderLog($orderLogList);

            foreach ($orderList as $order) {
                $this->TradeOrderDetailDao->handleThaw($order['orderId'], $update['handleStatus'] + 1, $order['transAmount']);
            }

        } catch (\Throwable $e) {
            Db::rollBack();
            throw $e;
        }

        Db::commit();

        // 通知出入账
        foreach ($orderList as $order) {
            $this->SettleService->addMq($order['mchId'], [
                'accessType'   => SettleAccessType::ACCESS_TYPE_TRADE_ORDER_THAW,
                'thawId'       => $order['id'],
                'handleStatus' => $update['handleStatus'],
                'mchNo'        => $order['mchNo'],
                'tradeNo'      => $order['tradeNo'],
            ]);
        }

        return CustomUtils::buildSuccess();
    }

    /**
     * 冻结订单审核
     *
     * @param $params
     *
     * @return array
     * @throws \Throwable
     */
    public function handleFrozenReview ($params) {

        $OrderDao = $this->TradeOrderFrozenDao;

        $isApprove   = Arr::get($params, 'isApprove');
        $reviewLevel = Arr::get($params, 'reviewLevel');

        $mchIdList   = Arr::get($params, 'mchIdList', null);
        $tradeNoList = Arr::get($params, 'tradeNoList', []);
        $tradeNoList = array_unique($tradeNoList);

        // 查询冻结订单
        $orderList = $this->_getOrderList($OrderDao, $tradeNoList, $mchIdList);

        // 筛选出无效tradeNo列表
        $failTradeNoList = $this->_filterFailTradeNoList($tradeNoList, $orderList, $reviewLevel);

        if (!empty($failTradeNoList)) {
            // 返回错误信息
            return CustomUtils::buildError(XZXResponseCode::getMessage(XZXResponseCode::UNQUALIFIED_ORDER), XZXResponseCode::FAILED_CODE, ['failTradeNoList' => $failTradeNoList]);
        }

        Db::beginTransaction();

        try {

            // 更新订单审核状态
            $update = $this->_parseStatusParams($reviewLevel, $isApprove, $params['createBy'], $params['remark']);

            $idList = array_column($orderList, 'id');
            $OrderDao->updateWhere(function (Builder $builder) use ($idList) {
                $builder->whereIn('id', $idList);
            }, $update);

            // 写入交易变更日志
            $orderLogList = [];
            foreach ($orderList as $order) {
                array_push($orderLogList, array_merge($order, $update, ['createBy' => $params['createBy']]));
            }
            ApplicationContext::getContainer()->get(TradeOrderFrozenService::class)->addOrderLog($orderLogList);

            // 更新订单详情
            foreach ($orderList as $order) {
                $this->TradeOrderDetailDao->handleFrozen($order['orderId'], $update['handleStatus'] + 1, $order['transAmount']);
            }

        } catch (\Throwable $e) {
            Db::rollBack();
            throw $e;
        }

        Db::commit();

        // 通知出入账
        foreach ($orderList as $order) {
            $this->SettleService->addMq($order['mchId'], [
                'accessType'   => SettleAccessType::ACCESS_TYPE_TRADE_ORDER_FROZEN,
                'frozenId'     => $order['id'],
                'handleStatus' => $update['handleStatus'],
                'mchNo'        => $order['mchNo'],
                'tradeNo'      => $order['tradeNo'],
            ]);
        }

        return CustomUtils::buildSuccess();
    }

    /**
     * 当前审核操作是否影响订单金额
     *
     * @param $isApprove   bool 是否审核通过
     * @param $reviewLevel int 审核次数
     *
     * @return bool
     */
    protected function _isAffectAmount ($isApprove, $reviewLevel) {

        if (!$isApprove) {
            // 审核驳回, 影响订单金额
            return true;
        }
        else {
            // 审核通过
            if (!$this->_isFirstReview($reviewLevel)) {
                // 复审
                return true;
            }
        }

        return false;
    }

    /**
     * 根据订单状态, 找出无效的ID
     *
     * @param $idList      array 传入的ID列表
     * @param $orderList   array 根据ID列表查询到的订单列表
     * @param $reviewLevel int 当前审核次数
     *
     * @return array
     */
    protected function _filterFailIdList ($idList, $orderList, $reviewLevel) {


        $failIdList = [];

        // 找出没有数据的tradeNo
        $foundIdList    = array_column($orderList, 'id');
        $notFoundIdList = array_diff($idList, $foundIdList);

        foreach ($notFoundIdList as $id) {
            array_push($failIdList, [
                'id'     => $id,
                'reason' => '数据不存在',
            ]);
        }

        // 遍历检查订单列表,检查订单状态是否有效(满足审核操作)
        foreach ($orderList as $order) {

            $tradeNo = $order['tradeNo'];

            [$canReview, $reason] = $this->_canReview($order, $reviewLevel);

            if (!$canReview) {
                array_push($failIdList, [
                    'id'      => $order['id'],
                    'tradeNo' => $tradeNo,
                    'reason'  => $reason,
                ]);
            }
        }

        return $failIdList;
    }

    /**
     * @param $tradeNoList array 传入的tradeNo列表
     * @param $orderList   array 根据tradeNo列表查询到的订单列表
     * @param $reviewLevel int 当前审核次数
     *
     * @return array
     * 找出无效的tradeNo
     */
    protected function _filterFailTradeNoList ($tradeNoList, $orderList, $reviewLevel) {

        $failTradeNoList = [];

        // 找出没有数据的tradeNo
        $foundTradeNoList    = array_column($orderList, 'tradeNo');
        $notFoundTradeNoList = array_diff($tradeNoList, $foundTradeNoList);

        foreach ($notFoundTradeNoList as $tradeNo) {
            array_push($failTradeNoList, [
                'tradeNo' => $tradeNo,
                'reason'  => '数据不存在',
            ]);
        }

        // 遍历检查订单列表,检查订单状态是否有效(满足审核操作)
        foreach ($orderList as $order) {

            $tradeNo = $order['tradeNo'];

            [$canReview, $reason] = $this->_canReview($order, $reviewLevel);

            if (!$canReview) {
                array_push($failTradeNoList, [
                    'tradeNo' => $tradeNo,
                    'reason'  => $reason,
                ]);
            }
        }

        return $failTradeNoList;
    }

    /**
     * 验证该订单是否满足审核条件
     *
     * @param $order
     * @param $reviewLevel
     *
     * @return array
     */
    protected function _canReview ($order, $reviewLevel) {

        $bool   = true;
        $reason = '';

        if (!$this->_isSettled($order)) {
            $bool   = false;
            $reason = '出入账处理未完成';
        }
        else {

            if ($this->_isReviewed($order, $reviewLevel)) {
                $bool   = false;
                $reason = '不处于待审核状态';
            }
            else {
                if (!$this->_isFirstReview($reviewLevel)) {
                    // 复审
                    if (!($order['handleStatus'] == OrderHandleStatusEnum::FIRST_APPROVE && $order['reviewStatus'] == OrderReviewStatusEnum::APPROVE)) {
                        // 初审未通过
                        $bool   = false;
                        $reason = '初审未通过';
                    }
                }
            }

        }

        return [$bool, $reason];
    }

    protected function _parseStatusParams ($reviewLevel, $isApprove, $reviewBy, $remark = '') {

        $update = [];

        if ($this->_isFirstReview($reviewLevel)) {
            // 初审
            $update['handleStatus'] = $isApprove ? OrderHandleStatusEnum::FIRST_APPROVE : OrderHandleStatusEnum::FIRST_REJECT;
            $update['reviewStatus'] = $isApprove ? OrderReviewStatusEnum::APPROVE : OrderReviewStatusEnum::REJECT;
            $update['reviewRemark'] = $remark;
            $update['reviewBy']     = $reviewBy;
            $update['reviewTime']   = time();
        }
        else {
            // 复审
            $update['handleStatus']   = $isApprove ? OrderHandleStatusEnum::SECOND_APPROVE : OrderHandleStatusEnum::SECOND_REJECT;
            $update['reReviewStatus'] = $isApprove ? OrderReviewStatusEnum::APPROVE : OrderReviewStatusEnum::REJECT;
            $update['reReviewRemark'] = $remark;
            $update['reReviewBy']     = $reviewBy;
            $update['reReviewTime']   = time();
        }

        $update['settleStatus'] = OrderSettleStatusEnum::INIT;

        return $update;
    }

    /**
     * 当前订单是否已审核
     *
     * @param $order       array 订单
     * @param $reviewLevel int 审核次数
     *
     * @return bool
     */
    protected function _isReviewed ($order, $reviewLevel) {

        if ($this->_isFirstReview($reviewLevel)) {
            // 初审
            return in_array($order['handleStatus'], [
                    OrderHandleStatusEnum::FIRST_APPROVE,
                    OrderHandleStatusEnum::FIRST_REJECT,
                ]) && $order['reviewStatus'] != OrderReviewStatusEnum::INIT;
        }
        else {
            // 复审
            return in_array($order['handleStatus'], [
                    OrderHandleStatusEnum::SECOND_APPROVE,
                    OrderHandleStatusEnum::SECOND_REJECT,
                ]) && $order['reReviewStatus'] != OrderReviewStatusEnum::INIT;
        }
    }

    /**
     * 出入账处理状态
     *
     * @param $order
     *
     * @return bool
     */
    protected function _isSettled ($order) {
        return $order['settleStatus'] == OrderSettleStatusEnum::DONE;
    }

    protected function _isFirstReview ($reviewLevel) {
        return $reviewLevel == 1;
    }


}
